import { Middleware } from "koa";
import { ObjectId } from "mongodb";

import { stats } from "../libs/stats";
import * as userService from "../services/user.service";

// 白名单
const white: string[] = [
  "/api/user/login",
  "/api/user/register"
];

/**
 * 登陆检查中间件
 * @param ctx
 * @param next
 */
const loginFilter: Middleware = async (ctx, next) => {
  for (let i = 0; i < white.length; i++) {
    if (ctx.url.includes(white[i])) {
      return next();
    }
  }

  // auth接口无需登陆拦截
  if (ctx.originalUrl.includes("auth")) console.log(ctx.originalUrl);

  // 获取token并判空
  const token = ctx.cookies.get("session_id");
  console.log("loginFillter - token: ", token);
  if (token === "" || token === undefined) throw stats.ErrSessionNotFound;

  // 根据session获取所有用户信息
  const user = await userService.getAllUserInfo(token);
  console.log("loginFillter - user: ", user);
  ctx.state.user = user;
  await next();
};

export default loginFilter;
